const mongoose=require('mongoose');
const Cate=require('../models/cate.model');


//增加
exports.create=function(req,res,next){
    const cate=new Cate(req.body);
    cate.save().then(data=>{
        res.json(data);
    })
}

//update
exports.update=function(req,res,next){
    const id=req.params.id;
    
    Cate.findByIdAndUpdate(id,{$set:req.body},{ new: false }).then(data=>{
        res.json(data);
    });
}


/*exports.tree=function(req,res,next){
    var type=req.params.type;
    Cate.find({type:type},function(err,data){
        //实现递归
        var rpTree=reverseTree(data,null);
        res.json(rpTree);
    })
}*/


exports.remove=function(req,res,next){
    var id=req.params.id;
    var ids=[];
    Cate.findOne({_id: id},function(err,doc){
        if(doc){
            ids=[doc._id];
            doc.getChildren().then(function(docs){
                for(var i=0;i<docs.length;i++){
                    ids.push(docs[i]._id);
                }
                Cate.remove({_id: {$in: ids}}).then(data=>{
                    res.json({status:200,message:'删除成功'});
                })
            })
        }
    })
}


function reverseTree(data,pid){
    var result=[],
    temp;

    var data=JSON.parse(JSON.stringify(data));
    //将数据模型的对象转成字符串,在将字符串转成对象，这时对象就成了javascript的普通Object
    for(var i in data){
        if(data[i].parentId === pid){//如果数据的parentId等于传递进来的pid参数
            result.push(data[i]);

            temp = reverseTree(data,data[i]._id);
            if(temp.length>0){
                data[i].children=temp;
            }
        }
    }
    return result;
}


//查
exports.list=function(req,res,next){
    const type=req.params.type;
    Cate.find({type:type},function(err,data){
        var rpTree=reverseTree(data,null);
        res.json(rpTree);
    })
}
